package Myresponse;

import Man.UserMapper;
import Util.Tool;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
@WebServlet("/Tom/registerServlet")
public class registerServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user=new User();
        user.setUsername(username);
        user.setPassword(password);

        SqlSessionFactory sqlSessionfactory = Tool.getsqlSessionFactory();
        SqlSession sqlSession=sqlSessionfactory.openSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);

        User u=userMapper.selectByName(username);
        if(u==null){
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer=resp.getWriter();

            userMapper.add(user);
            sqlSession.commit();
            sqlSession.close();

            writer.write("注册成功");
        }else {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("用户名已存在");
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
